﻿using System;
using System.Text.RegularExpressions;
using ShureValidation.Language;

namespace ShureValidation.Rules
{
    /// <summary>
    /// Validates that a value is a correct email address.
    /// </summary>
    /// <para>
    /// Language file items:
    /// <list type="table">
    ///     <listheader>
    ///         <term>ItemName</term>
    ///         <description>Language text</description>
    ///     </listheader>
    ///     <item>
    ///         <term>Email</term>
    ///         <description>'{0}' must be a valid email address.</description>
    ///     </item>
    /// </list>
    /// </para>
    [LanguagePrompt("Email", "'{0}' must contain a valid email address.")]
    [Serializable]
    public class EmailRule : IRule
    {
        private const string EmailRegEx = @"^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9_\.\-]+\.[a-zA-Z]{2,4}$";

        #region IRule Members

        /// <summary>
        /// Validate a field value
        /// </summary>
        /// <param name="value">Value to validate</param>
        /// <returns><c>true</c> if validation was successful; otherwise <c>false</c>.</returns>
        /// <exception cref="NotSupportedException">Only string types are supported.</exception>
        public bool Validate(object value)
        {
            if (value == null)
                return true;

            if (value is string)
            {
                var email = (string) value;
                return string.IsNullOrEmpty(email) || Regex.IsMatch(email, EmailRegEx);
            }

            throw new NotSupportedException(value.GetType() + " is not supported.");
        }

        /// <summary>
        /// Format an error message
        /// </summary>
        /// <param name="fieldName">Field (have already been translated)</param>
        /// <param name="rulesLanguage">Language prompts for validation rules</param>
        /// <returns>Error message formatted for the current language.</returns>
        public string Format(string fieldName, IModelLanguage rulesLanguage)
        {
            return string.Format(rulesLanguage["Email"], fieldName);
        }

        /// <summary>
        /// Checks if this rule support values of the specified format.
        /// </summary>
        /// <param name="type">Type of value</param>
        /// <returns><c>true</c> if the specified type can be validated; otherwise <c>false</c>.</returns>
        public bool SupportsType(Type type)
        {
            return typeof (string).IsAssignableFrom(type);
        }

        #endregion
    }
}